﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.SharePoint;
using Microsoft.VisualStudio.Shell;
using PS.WSSDeploy.Client;
using PS_WSSDeploy_Package.Utils;

namespace PS_WSSDeploy_Package.Application
{
    public class SharePointProjectItem
    {
        public string Name { get; set; }

        public string FullPath { get; set; }

        public string DeploymentLocation { get; set; }

        public Guid ProjectItemId { get; set; }

        public override string ToString()
        {
            return string.Format("[Name:'{0}', ProjectItemId:'{1}']", Name, ProjectItemId);
        }
    }

    public static class SharePointProjectManager
    {
        private static ISharePointProjectService _service;

        private static ISharePointProjectService Service
        {
            get { return _service ?? (_service = GetService()); }
        }

        private static ISharePointProjectService GetService()
        {
            return (ISharePointProjectService)Package.GetGlobalService(typeof(ISharePointProjectService));
        }
        
        public static bool IsSharePointProject(string projectFullName)
        {
            return Service.Projects[projectFullName] != null;
        }

        public static bool IsSharePointSandboxProject(string projectFullName)
        {
            var sharepointProject = Service.Projects[projectFullName];
            var value = sharepointProject != null && sharepointProject.IsSandboxedSolution;
            return value;
        }

        public static void BuildPackage(string projectFullName)
        {
            Service.Projects[projectFullName].Package.BuildPackage();
        }

        public static string GetWspFullPath(string projectFullName)
        {
            var ret = Service.Projects[projectFullName].Package.OutputPath;
            return ret;
        }

        public static string GetWspName(string projectFullName)
        {
            string ret = string.Empty;
            try
            {
                ret = Service.Projects[projectFullName].Package.Model.Name + Constants.WspExt;
            }
            catch
            {
            }
            return ret;
        }

        public static List<RootFile> GetRootFiles(string projectName)
        {
            var rootFiles = new List<RootFile>();
            var projectItems = new List<SharePointProjectItem>();
            var featureItems = new Dictionary<Guid, string>();
            var duplicateFilter = new List<string>();

            var spProjects = Service.Projects;
            foreach (var spProject in spProjects)
            {
                if (spProject.Name != projectName && !string.IsNullOrEmpty(projectName)) continue;

                foreach (var item in spProject.ProjectItems)
                {
                    foreach (var file in item.Files)
                    {
                        if (!string.IsNullOrEmpty(file.DeploymentRoot) && !duplicateFilter.Contains(file.FullPath))
                        {
                            projectItems.Add(new SharePointProjectItem
                                                 {
                                                     Name = file.Name,
                                                     FullPath = file.FullPath,
                                                     DeploymentLocation =
                                                         string.Concat(file.DeploymentRoot, file.DeploymentPath),
                                                     ProjectItemId = file.ProjectItem.Id
                                                 });

                            duplicateFilter.Add(file.FullPath);
                        }
                    }
                }

                foreach (var feature in spProject.Features)
                {
                    foreach (var item in feature.ProjectItems)
                    {
                        featureItems.Add(item.Id, feature.Name);
                    }
                }

                foreach (var featureItem in featureItems)
                {
                    foreach (var projectItem in projectItems)
                    {
                        if (projectItem.ProjectItemId == featureItem.Key)
                        {
                            projectItem.DeploymentLocation =
                                projectItem.DeploymentLocation.Replace(Constants.FeatureNameToken,
                                                                       featureItem.Value);
                        }
                    }
                }
            }

            foreach (var projectItem in projectItems)
            {
                if (projectItem.DeploymentLocation.Contains(Constants.FeatureNameToken)) continue;

                rootFiles.Add(
                    new RootFile
                    {
                        Path = projectItem.FullPath,
                        DeploymentPath = string.Concat(
                            projectItem.DeploymentLocation.Replace(Constants.RootToken, string.Empty),
                            projectItem.Name)
                    });
            }

            return rootFiles;
        }

        public static List<RootFile> GetRootFileForItem(string projectItemFullPath)
        {
            var ret = new List<RootFile>();

            var rootFiles = GetRootFiles(null);

            foreach (var rootFile in rootFiles)
            {
                if (rootFile.Path.Equals(projectItemFullPath))
                {
                    ret.Add(rootFile);
                    break;
                }
                if (rootFile.Path.StartsWith(projectItemFullPath))
                {
                    ret.Add(rootFile);
                }
            }

            return ret;
        }

        public static List<RootFile> GetRootFilesForWdItems(List<WdProjectItem> projectItems)
        {
            var ret = new List<RootFile>();

            var rootFiles = GetRootFiles(null);
            
            foreach (var rootFile in rootFiles)
            {
                foreach (var projectItem in projectItems)
                {
                    if (rootFile.Path.Equals(projectItem.FullPath))
                    {
                        if(!ret.Contains(rootFile)) ret.Add(rootFile);
                    }
                    else if (rootFile.Path.StartsWith(projectItem.FullPath))
                    {
                        if (!ret.Contains(rootFile)) ret.Add(rootFile);
                    }
                }
            }

            return ret;
        }

        public static void ReplaceToken(SpFileToken token, string value, List<RootFile> rootFiles)
        {
            foreach (var rootFile in rootFiles)
            {
                var content = File.ReadAllBytes(rootFile.Path);
                var contentStr = StringUtils.ByteArrayToStr(content);
                var newContent = contentStr.Replace(SpFileTokenString.Get(token), value);
                rootFile.Content = StringUtils.StrToByteArray(newContent);
            }
        }
    }
}
